<template>
  <div class="container">
    <el-container>
      <!-- 头部 区域 -->
      <el-header class="new_header">
        <!-- 标题 -->
        <span>试题录入</span>
      </el-header>
      <!-- 主体区域 -->
      <el-main>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleFormref"
          label-width="155px"
          class="demo-ruleForm"
        >
          <!-- 学科 -->
          <el-form-item label="学科：" prop="subjectID">
            <el-select
              v-model="ruleForm.subjectID"
              placeholder="请选择"
              @change="handleSubject"
              filterable
            >
              <el-option
                :label="item.subjectName"
                :value="item.id"
                v-for="(item, index) in subjects"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item label="目录：" prop="catalogID">
            <el-select v-model="ruleForm.catalogID" placeholder="请选择">
              <el-option
                :label="catalogID.directoryName"
                :value="catalogID.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select v-model="ruleForm.enterpriseID" placeholder="请选择">
              <el-option
                :label="item.shortName"
                :value="item.id"
                v-for="(item, index) in companyList"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <el-form-item label="城市：" prop="province">
            <!-- 第一个下拉 -->
            <el-select
              placeholder="请选择"
              class="city_select"
              v-model="ruleForm.province"
              @keyup.enter="handleFilter"
              @change="handleProvince"
              filterable
            >
              <el-option
                v-for="item in citySelect.province"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <!-- 第二个下拉 -->
            <el-select
              v-model="ruleForm.city"
              @keyup.enter="handleFilter"
              filterable
              placeholder="请选择"
              class="city_select_two"
            >
              <el-option
                v-for="item in citySelect.cityDate"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item label="方向：" prop="direction">
            <el-select v-model="ruleForm.direction" placeholder="请选择">
              <el-option
                :label="item.direction"
                :value="item.difficulty"
                v-for="(item, index) in direction"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item label="题型：" prop="questionType">
            <div @change="radioNew">
              <el-radio v-model="ruleForm.questionType" label="1"
                >单选</el-radio
              >
              <el-radio v-model="ruleForm.questionType" label="2"
                >多选</el-radio
              >
              <el-radio v-model="ruleForm.questionType" label="3"
                >简答</el-radio
              >
            </div>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item label="难度：" prop="difficulty">
            <div @change="isUpload = false">
              <el-radio v-model="ruleForm.difficulty" label="1">简单</el-radio>
              <el-radio v-model="ruleForm.difficulty" label="2">一般</el-radio>
              <el-radio v-model="ruleForm.difficulty" label="3">困难</el-radio>
            </div>
          </el-form-item>
          <!-- 题干 富文本 -->
          <el-form-item label="题干：" prop="question">
            <!-- 富文本编辑器组件 -->
            <!-- <quill-editor v-model="addForm.goods_introduce"></quill-editor> -->
            <quill-editor
              class="ql-editor"
              v-model="ruleForm.question"
              ref="myQuillEditor"
              :options="editorOption"
            ></quill-editor>
            <!--/ 富文本编辑器组件 -->
          </el-form-item>
          <!-- 选项 -->
          <el-form-item label="选项：">
            <!-- 单选 -->
            <template v-if="ruleForm.questionType === '1'">
              <div v-for="(item, index) in arr" :key="index">
                <el-row v-if="index < 4">
                  <el-col>
                    <el-form-item label-width="120px">
                      <el-row>
                        <el-col :span="1">
                          <el-radio :label="index" v-model="radio"
                            >{{ item.code }}：</el-radio
                          >
                        </el-col>
                        <el-col :span="5">
                          <el-input v-model="item.title"></el-input>
                        </el-col>
                        <el-col :span="10">
                          <el-upload
                            class="upload-demo"
                            action="#"
                            multiple
                            :limit="3"
                          >
                            <el-button class="upload_btn">点击上传</el-button>
                          </el-upload>
                        </el-col>
                      </el-row>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
              <el-row>
                <el-col>
                  <el-button
                    class="add_btn"
                    type="danger"
                    size="small"
                    @click="addItem"
                    disabled
                    >+增加选项与答案</el-button
                  >
                </el-col>
              </el-row>
            </template>

            <!-- 多选 -->
            <template v-if="ruleForm.questionType === '2'">
              <div v-for="(item, index) in arr" :key="index">
                <el-checkbox-group v-model="checkList">
                  <el-row v-if="index < questionIndex">
                    <el-col>
                      <el-form-item label-width="120px">
                        <el-row>
                          <el-col :span="1">
                            <el-checkbox :label="index">{{
                              item.code
                            }}</el-checkbox>
                          </el-col>
                          <el-col :span="5">
                            <el-input v-model="item.title"></el-input>
                          </el-col>
                          <el-col :span="10">
                            <el-upload
                              class="upload-demo"
                              action="#"
                              multiple
                              :limit="3"
                            >
                              <el-button class="upload_btn">点击上传</el-button>
                            </el-upload>
                          </el-col>
                        </el-row>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
              <el-row>
                <el-col>
                  <el-button
                    class="add_btn"
                    type="danger"
                    size="small"
                    @click="addItem"
                    >+增加选项与答案</el-button
                  >
                </el-col>
              </el-row>
            </template>
          </el-form-item>

          <!-- 解析视频 -->
          <el-form-item label="解析视频：">
            <el-input class="el-select" v-model="ruleForm.videoURL"></el-input>
          </el-form-item>

          <!-- 答案解析 富文本 -->
          <el-form-item label="答案解析：" prop="answer">
            <!-- 富文本编辑器组件 -->
            <quill-editor
              class="ql-editor"
              v-model="ruleForm.answer"
              ref="twoQuillEditor"
              :options="editorOption"
            ></quill-editor>
            <!--/ 富文本编辑器组件 -->
          </el-form-item>

          <!-- 题目备注 -->
          <el-form-item label="题目备注：">
            <textarea
              name
              id
              cols="10"
              rows="10"
              class="el-select_tet"
              v-model="ruleForm.remarks"
            ></textarea>
          </el-form-item>

          <!-- 试题标签 -->
          <el-form-item label="试题标签：">
            <el-select
              multiple
              allow-create
              v-model="ruleForm.tags"
              placeholder="请选择试题标签"
            >
              <el-option
                :label="item.tagName"
                :value="index"
                v-for="(item, index) in tagList"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 确定按钮 -->
          <el-form-item>
            <el-button
              :type="$route.params.id ? 'success ' : 'primary'"
              @click="onClick($event)"
              >{{ $route.params.id ? '确认修改' : '确认提交' }}</el-button
            >
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { list as subjects } from '@/api/hmmm/subjects'
import { list as companys } from '@/api/hmmm/companys'
import {
  list as questions,
  add,
  update as dupdate,
  detail as edit
} from '@/api/hmmm/questions'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { detail as directorys, list as dlist } from '@/api/hmmm/directorys'
import { detail as tagsDetail } from '@/api/hmmm/tags'
import { array } from '@/api/hmmm/constants'
import hljs from 'highlight.js'
import 'highlight.js/styles/xcode.css'
export default {
  name: 'questionNew',
  data() {
    return {
      ruleForm: {
        subjectID: '', // 学科
        enterpriseID: '', // 企业
        direction: '', // 方向
        catalogID: '', // 目录
        questionType: '1', // 题型
        difficulty: '1', // 难度
        checkList: [], // 图片
        province: '', // 省份
        city: '', // 城市
        // 富文本
        question: '', // 题干
        answer: '', // 答案解析
        options: [], // 选项
        videoURL: ' ', // 解析视频
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [{ required: true, message: '请填写题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请填写答案解析', trigger: 'blur' }]
      },
      checkList: [], // 复选框列表
      radio: '', // 单选
      questionIndex: 4, // 选项存储的index
      arr: array, // 存储选项的数组
      companyList: [], // 企业列表
      activeName: 'all', // 标签页活动值
      questionItem: {}, // 预览时传入子组件的试题
      dialogVisible: false, // 试题预览
      questionList: [], // 题库列表
      citys: [], // 区域列表
      citySelect: {
        province: [],
        cityDate: []
      },
      tagList: [], // 标签列表
      userList: [], // 录入人列表
      direction: [], // 方向
      // difficulty: {
      //   '1': '简单',
      //   '2': '一般',
      //   '3': '困难'
      // }, // 试题类型

      // questionType: {
      //   '1': '单选',
      //   '2': '多选',
      //   '3': '简答'
      // }, // 难度
      // 二级目录列表
      directory: [],
      // 学科列表
      subjects: [],
      catalogID: [],
      // 查询信息
      // 富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ script: 'sub' }, { script: 'super' }],
            [{ indent: '-1' }, { indent: '+1' }],
            [{ direction: 'rtl' }],
            [{ size: ['small', false, 'large', 'huge'] }],
            [{ header: [1, 2, 3, 4, 5, 6, false] }],
            [{ color: [] }, { background: [] }],
            [{ font: [] }],
            [{ align: [] }],
            ['clean'],
            ['link', 'image', 'video']
          ],
          syntax: {
            highlight: (text) => {
              return hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
            }
          }
        },
        placeholder: '' // 文本框为空时 , 占位文本
      }
    }
  },
  methods: {
    onClick(e) {
      this.$refs.ruleFormref.validate(async (valid) => {
        if (!valid) {
          this.$message.error('请确认必填选项完成')
          return false
        } else {
          this.arr = array
          this.$message.success('校验通过！')
          switch (e.target.innerText) {
            case '确认提交':
              this.onSubmit()
              this.$message.success('添加成功')
              break

            case '确认修改':
              this.ruleForm.tags = this.ruleForm.tags.join(',')
              switch (this.ruleForm.questionType) {
                // 单选
                case '1':
                  const optionArr = this.arr.slice(0, 4)
                  // 判断默认勾选
                  optionArr.forEach((item, index) => {
                    if (index === this.radio) {
                      item.isRight = true
                    } else {
                      item.isRight = false
                    }
                  })
                  this.ruleForm.options = optionArr.reverse()
                  break

                // 多选的情况
                case '2':
                  const arr = this.arr.slice(0, this.questionIndex)
                  // 判断默认勾选
                  for (let i = 0; i < arr.length; i++) {
                    this.checkList.forEach((item) => {
                      if (i === item) {
                        arr[i].isRight = true
                      }
                    })
                  }
                  this.form.options = arr.reverse()
                  break
              }
              const data = await dupdate(this.ruleForm)
              console.log(data)
              this.$message.success('修改成功')
              break
          }
          this.$router.push('list')
        }
      })
    },

    // 提交选项
    async onSubmit() {
      // 标签转字符串
      this.ruleForm.tags = this.ruleForm.tags.join(',')
      // 试题选项操作 处理数据
      switch (this.form.questionType) {
        // 单选
        case '1':
          const optionArr = this.arr.slice(0, 4)
          // 判断默认勾选
          optionArr.forEach((item, index) => {
            if (index === this.radio) {
              item.isRight = true
            } else {
              item.isRight = false
            }
          })
          this.form.options = optionArr
          break

        // 多选的情况
        case '2':
          const arr = this.arr.slice(0, this.questionIndex)
          // 判断默认勾选
          for (let i = 0; i < arr.length; i++) {
            this.checkList.forEach((item) => {
              if (i === item) {
                arr[i].isRight = true
              }
            })
          }
          this.form.options = arr
          break
      }
      const { data } = await add(this.ruleForm)
      // if(data)
      console.log(data)
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 图片上传
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    // 获取学科数据
    async getNewList() {
      const { data } = await subjects()
      this.subjects = data.items
      // console.log(this.subjectList)
    },
    // 获取企业列表
    async getpriseList() {
      const { data } = await companys()
      this.companyList = data.items
      // console.log(this.companyList)
    },
    // 获取方向 目录
    async getquestions() {
      const { data } = await questions()
      this.direction = data.items
      // console.log(this.direction)
    },
    // 获取省
    getCityData: function () {
      this.citySelect.province = provinces()
    },
    // 选省获取到市
    handleProvince: function (e) {
      this.citySelect.cityDate = citys(e)
      // console.log(e)
      this.requestParameters.city = this.citySelect.cityDate[0]
    },
    // 选科目获取到目录
    async handleSubject(e) {
      // console.log(e)
      // 目录
      const { data } = await directorys({ id: e })
      const directory = data
      this.catalogID = directory
      console.log(this.catalogID)
      // 试题标签
      const { data: res } = await tagsDetail({ id: e })
      // console.log(res)
      this.tagList = res
    },
    radioNew() {
      this.isUpload = true
      if (this.questionRadio === '3') {
        // console.log('简单')
        this.ischeckout = false
      } else {
        this.ischeckout = true
      }
    },
    // 点击增加
    addItem() {
      if (this.questionIndex > 25) {
        return
      }
      this.questionIndex++
    },
    // 从基础题库跳转过来的
    async geteditlist() {
      const a = this.$route.params.id
      console.log(a)
      const { data } = await edit({ id: a })
      console.log(data)
      this.ruleForm = data
      this.ruleForm.tags = data.tags.split(',')
      this.questionIndex = this.ruleForm.options.length
      // // 重新加载添加按钮所需的容器
      const arrs = array
      // // 对添加按钮的数据进行处理
      const newArr = arrs.splice(+this.ruleForm.options.length)
      this.arr = this.ruleForm.options.concat(newArr)

      // 开始获取目录
      const { data: res } = await dlist({
        subjectID: this.ruleForm.subjectID
      })
      console.log(res)
      this.directory = res.items
      // 判断
      switch (this.ruleForm.questionType) {
        // 单选
        case '1':
          this.ruleForm.options.forEach((item, index) => {
            if (item.isRight === 1) {
              this.radio = index
            }
          })
          break
        // 多选
        case '2':
          this.ruleForm.options.forEach((item, index) => {
            if (item.isRight === 1) {
              this.checkList.push(index)
            }
          })
          break
      }
    }
  },
  created() {
    if (this.$route.query.id) {
      // 返回顶部
      this.backTop()
    }
    this.getNewList()
    this.getpriseList()
    this.getquestions()
    this.getCityData()
    this.geteditlist()
    console.log(this.arr)
    // 键盘enter操作
    var _this = this
    document.onkeydown = function (e) {
      var key = window.event.keyCode
      if (key === 13) {
        _this.handleFilter(this.requestParameters)
      }
    }
  },
  computed: {}
}
</script>

<style scoped lang="less">
.container {
  background-color: #fff;
  margin: 30px 23px 23px 23px;
  .new_header {
    height: 70px;
    display: flex;
    align-items: center;
    font-size: 20px;
    border-bottom: 1px solid #ebeef5;
  }
  .el-select {
    width: 500px;
  }
  .el-select_tet {
    width: 500px;
    height: 118px;
  }
  .city_select {
    width: 247px;
  }
  .city_select_two {
    width: 247px;
    margin-left: 6px;
  }
  .ql-editor {
    padding: 0;
  }
  /deep/ .ql-container {
    min-height: 230px;
  }
  /deep/ .new_checkout {
    display: flex;
    flex-direction: column;
  }

  .new_button {
    background-color: #fab6b6;
    color: #fff;
  }
  /deep/ .el-checkbox__label {
    display: flex;
    align-items: center;
  }
  /deep/ .new_checkout_a {
    .el-checkbox {
      display: flex;
      align-items: center;
    }
    .check_box {
      width: 295px;
      margin-bottom: 25px;
      margin-top: 20px;
      display: flex;
      line-height: 36px;
    }
    .el-upload {
      position: relative;
    }
    .el-icon-circle-close {
      position: absolute;
      top: -9px;
      right: -8px;
      font-size: 19px;
    }
  }

  .el-button--primary_a {
    width: 124px;
    height: 74px;
    background-color: #fff;
    border: 1px dashed #ccc;
    border-radius: 4px;
    color: #000;
    font-size: 16px;
  }
  .upload-demo {
    margin-left: 20px;
  }
}
.upload-demo {
  margin-left: 20px;
  .upload_btn {
    margin-top: -10px;
    height: 50px;
  }
}
.add_btn {
  margin: 10px 0px 20px;
  margin-left: 120px;
}
/deep/.el-form-item__content {
  margin-left: 80px !important;
}
.el-form-item .el-form-item {
  margin-bottom: 18px;
}
</style>
